import ujson as json
import network
import os
import time

class WifiConfig:
    def __init__(self, filename='wifi_config.json'):
        self.filename = filename
        self.default_config = {"def_wifi": {}, "wifi_list": {}}
        self.load_or_init_config()
        self.wlan = network.WLAN(network.STA_IF)
        self.wlan.active(True)

    def load_or_init_config(self):
        try:
            with open(self.filename, 'r') as f:
                print(f)
                config = json.load(f)
                print(config)
                self.config = config
        except OSError:
            print("文件不存在:", self.filename)
            self.config = self.default_config
            self.save_config()

        print("初始化wifi信息", self.config)

    def save_config(self):
        with open(self.filename, 'w') as f:
            json.dump(self.config, f)

    def add_wifi_info(self, ssid, password):
        self.config["wifi_list"][ssid] = password
        self.save_config()

    def add_def_wifi(self, ssid, password):
        self.config["def_wifi"][ssid] = password
        self.save_config()

    def delete_wifi_info(self, ssid):
        try:
            self.config["wifi_list"].pop(ssid)
        except:
            print("删除失败")
            return
        self.save_config()

    def connect_wifi(self, ssid, password):
        wlan = self.wlan
        cnt = 10
        if wlan.isconnected():
            print("网络已经连接")
            print('网络配置：', wlan.ifconfig())
            return True

        print("连接wifi[", ssid, ":", password, "]", end="")
        wlan.connect(ssid, password)
        while not wlan.isconnected():
            print(".", end="")
            time.sleep(1)
            cnt -= 1
            if cnt == 0:
                break

        if wlan.isconnected():
            print("成功")
            print('网络配置：', wlan.ifconfig())
            return True
        else:
            print("失败")
            print('网络配置：', wlan.ifconfig())
            return False

    def connect_all_wifi(self):
        for ssid, passwd in self.config["def_wifi"].items():
            print("连接默认wifi[{}：{}]".format(ssid, passwd))
            if self.connect_wifi(ssid, passwd):
                return True

        for ssid, passwd in self.config["wifi_list"].items():
            if self.connect_wifi(ssid, passwd):
                self.add_def_wifi(ssid, passwd)
                return True
        else:
            print("没有找到能够连接的wifi")
            return False

    def ap_mode(self, ssid, password):
        wlan = network.WLAN(network.AP_IF)
        wlan.active(True)
        wlan.config(essid=ssid, password=password)
        print('切换到接入点（access point）模式...')
        print('当前模式:', 'access point' if wlan.active() else 'unknown')
        print('AP配置:', wlan.ifconfig())


def test():
    # 测试
    wifi_manager = WifiConfig()

    # 如果没有保存的WiFi配置，提示用户设置
    wifi_manager.add_wifi_info("becky4", "1234445")
    wifi_manager.add_wifi_info("bec3ky", "1234445")
    wifi_manager.add_wifi_info("be2cky", "1234445")
    wifi_manager.add_wifi_info("becky", "becky1be1cky")
    wifi_manager.add_wifi_info("bec5ky", "1234445")
    wifi_manager.add_wifi_info("bec6ky", "1234445")
    # 打印当前的WiFi配置
    print("当前的WiFi配置:", wifi_manager.config)

    # 添加一个WiFi网络配置
    # wifi_manager.add_wifi_info("NewSSID", "NewPassword")

    # 删除一个WiFi网络配置
    # wifi_manager.delete_wifi_info("SSIDtoDelete")

    # 将某个WiFi信息放到字典头部
    # wifi_manager.move_wifi_to_top("WiFiSSID")

    # 连接所有WiFi直到成功
    if not wifi_manager.connect_all_wifi():
        wifi_manager.ap_mode("abcde","sdafsdafdsa")
